package com.example.springboottools.utils;

import com.alibaba.fastjson.JSON;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import org.apache.http.HttpStatus;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * pdf盖章工具类
 */
public class StampUtil {

    public static void main(String[] args) {
        String source = "D:\\staples\\日常记录\\工作记录\\2024\\07\\pod盖章及缓存\\test\\source\\pod4507092398.pdf";
        String target = "D:\\staples\\日常记录\\工作记录\\2024\\07\\pod盖章及缓存\\test\\target\\pod4507092398.pdf";
        String keyword = "直送日期";
        String image = "D:\\staples\\日常记录\\工作记录\\2024\\07\\pod盖章及缓存\\test\\delivery_stamp.png";
        float xOffset = 80;
        float yOffset = -30;
        float scale = 60;
        try {
            File file = new File(source);
            byte[] pdfData = Files.readAllBytes(Paths.get(file.getPath()));
            File imageFile = new File(image);
            byte[] imageBytes = Files.readAllBytes(Paths.get(imageFile.getPath()));
        //    Map<String, String> keyWordAndAddImage = StampUtil.findKeyWordAndAddImage(source, target, keyword, image, xOffset, yOffset, scale);
            byte[] keyWordAndAddImage = StampUtil.findKeyWordAndAddImage(pdfData, keyword, imageBytes, xOffset, yOffset, scale);
            FileOutputStream fos = new FileOutputStream(target);
            fos.write(keyWordAndAddImage);
            fos.flush();
            fos.close();
            System.out.println("盖章成功");
        } catch (Exception e) {
            System.out.println("盖章异常： " + JSON.toJSONString(e));
        }

    }
    /**
     * 寻找指定的关键字后给其所在位置盖章
     * @param source    源pdf文件
     * @param target    目标pdf文件
     * @param keyword   关键字
     * @param image     印章路径
     * @param xOffset   x轴偏移量(没有则指定为0)
     * @param yOffset   y轴偏移量(没有则指定为0)
     * @return          返回结果
     * @throws IOException
     * @throws DocumentException
     */
    public static Map<String, String> findKeyWordAndAddImage(String source, String target,
                                                             String keyword, String image, float xOffset,
                                                             float yOffset, float scale) throws IOException, DocumentException {

        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("code", String.valueOf(HttpStatus.SC_OK));
        boolean result = false;

        File pdfFile = new File(source);
        byte[] pdfData = new byte[(int) pdfFile.length()];

        try (FileInputStream fis = new FileInputStream(pdfFile)) {
            fis.read(pdfData);

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件不存在");
            resultMap.put("code", String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
            resultMap.put("message", "文件不存在");
            return resultMap;
        }

        //查到关键字返回位置
        List<float[]> positions = GetKeyWordPosition.findKeywordPostions(pdfData, keyword);
        if(positions.size() == 0){
            System.out.println(keyword + " 关键字不存在");
            resultMap.put("code", String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
            resultMap.put("message", "关键字不存在");
            return resultMap;
        }

        //添加水印 //会查询到多个关键字定位，固定取最后一个
        result = addImage(source, target,  image, positions.get(positions.size()-1), xOffset, yOffset,scale);
        return resultMap;
    }
    /**
     * 寻找指定的关键字后给其所在位置盖章
     * @param source    源pdf文件
     * @param target    目标pdf文件
     * @param keyword   关键字
     * @param image     印章路径
     * @param xOffset   x轴偏移量(没有则指定为0)
     * @param yOffset   y轴偏移量(没有则指定为0)
     * @return          返回结果
     * @throws IOException
     * @throws DocumentException
     */
    public static Map<String, String> findKeyWord(String source, String target,
                                                             String keyword, String image, float xOffset,
                                                             float yOffset, float scale) throws IOException, DocumentException {

        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("code", String.valueOf(HttpStatus.SC_OK));
        boolean result = false;

        File pdfFile = new File(source);
        byte[] pdfData = new byte[(int) pdfFile.length()];

        try (FileInputStream fis = new FileInputStream(pdfFile)) {
            fis.read(pdfData);

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件不存在");
            resultMap.put("code", String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
            resultMap.put("message", "文件不存在");
            return resultMap;
        }

        //查到关键字返回位置
        List<float[]> positions = GetKeyWordPosition.findKeywordPostions(pdfData, keyword);
        if(positions.size() == 0){
            System.out.println(keyword + " 关键字不存在");
            resultMap.put("code", String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
            resultMap.put("message", "关键字不存在");
            return resultMap;
        }

        //添加水印 //会查询到多个关键字定位，固定取最后一个
        result = addImage(source, target,  image, positions.get(positions.size()-1), xOffset, yOffset,scale);
        return resultMap;
    }


    public static boolean findKeyWordAndAddImage(byte[] pdfData, String target,
                                                 String keyword, String image, float xOffset,
                                                 float yOffset,float scale) throws IOException, DocumentException {
        boolean result = false;

        //查到关键字返回位置
        List<float[]> positions = GetKeyWordPosition.findKeywordPostions(pdfData, keyword);
        if(positions.size() == 0){
            System.out.println(keyword + " 关键字不存在");
            return result;
        }
        //添加图片 //会查询到多个关键字定位，固定取最后一个
        return addImage(pdfData, target,  image, positions.get(positions.size()-1), xOffset, yOffset,scale);
    }
    public static byte[] findKeyWordAndAddImage(byte[] pdfData,
                                                 String keyword,byte image[], float xOffset,
                                                 float yOffset,float scale) throws IOException, DocumentException {
        boolean result = false;

        //查到关键字返回位置
        List<float[]> positions = GetKeyWordPosition.findKeywordPostions(pdfData, keyword);
        if(positions.size() == 0){
            System.out.println(keyword + " 关键字不存在");
            return null;
        }
        //添加图片 //会查询到多个关键字定位，固定取最后一个
        return addImage(pdfData, image, positions.get(positions.size()-1), xOffset, yOffset,scale);
    }
    public static byte[] findKeyWordAndAddImageGetByte(byte[] pdfData, String target,
                                                       String keyword, String image, float xOffset, float yOffset,float scale) throws IOException, DocumentException {
        //查到关键字返回位置
        List<float[]> positions = GetKeyWordPosition.findKeywordPostions(pdfData, keyword);
        if(positions.size() == 0){
            System.out.println(keyword + " 关键字不存在");
            return null;
        }
        //添加水印 //会查询到多个关键字定位，固定取最后一个
        return addImageGetByte(pdfData, target,  image, positions.get(positions.size()-1), xOffset, yOffset,scale);
    }
    private static byte[] addImageGetByte(byte[] podPdfBytes, String target, String imagePath, float[] positions, float xOffset, float yOffset,float scale) throws IOException, DocumentException {
        // 读取模板文件
        addImage(podPdfBytes, target, imagePath, positions,xOffset,yOffset,scale);
        // 将生成的pdf文件输出为字节数组
        byte[] bytes = Files.readAllBytes(Paths.get(target));
        // 清理临时文件
        File file = new File(target);
        file.delete();
        return bytes;
    }
    private static boolean addImage(byte[] podPdfBytes, String target, String imagePath, float[] positions, float xOffset, float yOffset,float scale) throws IOException, DocumentException {
        // 读取模板文件
        InputStream input = new ByteArrayInputStream(podPdfBytes);
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));


        // 提取pdf中的表单
        AcroFields form = stamper.getAcroFields();
        form.addSubstitutionFont(BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));

        // 读图片
        Image image = Image.getInstance(imagePath);

        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent((int)positions[0]);

        //设置图片的定位
        image.setAbsolutePosition(positions[1]+xOffset, positions[2]+yOffset);


        image.scalePercent(scale); //缩放图片为指定百分比

        // 设置透明度为0.8
        PdfGState gs = new PdfGState();

        gs.setFillOpacity(0.8f);
        under.setGState(gs);
        // 添加图片
        under.addImage(image);

        stamper.close();
        reader.close();
        return true;
    }
    private static boolean addImage(byte[] podPdfBytes, String target, byte imgb[], float[] positions, float xOffset, float yOffset,float scale) throws IOException, DocumentException {
        // 读取模板文件
        InputStream input = new ByteArrayInputStream(podPdfBytes);
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));


        // 提取pdf中的表单
        AcroFields form = stamper.getAcroFields();
        form.addSubstitutionFont(BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));

        // 读图片
        Image image = Image.getInstance(imgb);

        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent((int)positions[0]);

        //设置图片的定位
        image.setAbsolutePosition(positions[1]+xOffset, positions[2]+yOffset);


        image.scalePercent(scale); //缩放图片为指定百分比

        // 设置透明度为0.8
        PdfGState gs = new PdfGState();

        gs.setFillOpacity(0.8f);
        under.setGState(gs);
        // 添加图片
        under.addImage(image);

        stamper.close();
        reader.close();
        return true;
    }
    private static byte[] addImage(byte[] podPdfBytes, byte imgb[], float[] positions, float xOffset, float yOffset,float scale) throws IOException, DocumentException {
        // 读取模板文件
        InputStream input = new ByteArrayInputStream(podPdfBytes);
        PdfReader reader = new PdfReader(input);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, byteArrayOutputStream);


        // 提取pdf中的表单
        AcroFields form = stamper.getAcroFields();
        form.addSubstitutionFont(BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));

        // 读图片
        Image image = Image.getInstance(imgb);

        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent((int)positions[0]);

        //设置图片的定位
        image.setAbsolutePosition(positions[1]+xOffset, positions[2]+yOffset);


        image.scalePercent(scale); //缩放图片为指定百分比

        // 设置透明度为0.8
        PdfGState gs = new PdfGState();

        gs.setFillOpacity(0.8f);
        under.setGState(gs);
        // 添加图片
        under.addImage(image);

        stamper.close();
        reader.close();
        return byteArrayOutputStream.toByteArray();
    }
    //添加水印(签章)
    private static boolean addImage(String source, String target, String imagePath, float[] positions, float xOffset, float yOffset,float scale) throws IOException, DocumentException {
        // 读取模板文件
        InputStream input = new FileInputStream(source);
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));


        // 提取pdf中的表单
        AcroFields form = stamper.getAcroFields();
        form.addSubstitutionFont(BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));

        // 读图片
        Image image = Image.getInstance(imagePath);

        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent((int)positions[0]);

        //设置图片的定位
        image.setAbsolutePosition(positions[1]+xOffset, positions[2]+yOffset);


        image.scalePercent(scale); //缩放图片为指定百分比

        // 设置透明度为0.8
        PdfGState gs = new PdfGState();

        gs.setFillOpacity(0.8f);
        under.setGState(gs);
        // 添加图片
        under.addImage(image);

        stamper.close();
        reader.close();
        return true;
    }
}
